package com.ycy.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;


import com.google.api.client.http.json.JsonHttpRequest;
import com.google.api.client.http.json.JsonHttpRequestInitializer;
import com.google.api.services.plus.Plus;
import com.google.api.services.plus.PlusRequest;
import com.google.api.services.plus.model.Activity;
import com.google.api.services.plus.model.ActivityFeed;
import com.ycy.ss.Constant;
import com.ycy.ss.status.AllStatus;
import com.ycy.ss.status.StatusGoogle;
import com.ycy.util.GoogleUtil;

/**
 * 此consumer为只读，不需要认证。
 * A servlet which handles the OAuth 2.0 authentication result and retrieves an access token on successful
 * authentication.
 * 
 * @author Jennifer Murphy
 * @author Lee Denison
 */
public class GoogleJustReadConsumer extends HttpServlet{

	private static final long serialVersionUID = 1L;

	private static final Logger log = Logger.getLogger(GoogleJustReadConsumer.class);

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
		if ("1".equals(request.getParameter("clear"))) {
			AllStatus.google = null;
			response.getWriter().write("clear");
			return;
		}
		
		StatusGoogle statusGoogle = new StatusGoogle();
		
		Plus.Builder builder = new Plus.Builder(GoogleUtil.TRANSPORT, GoogleUtil.JSON_FACTORY, null);
		Plus unauthenticatedPlus = builder.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer(){
			public void initialize(JsonHttpRequest jsonHttpRequest) throws IOException{
				PlusRequest plusRequest = (PlusRequest) jsonHttpRequest;
				plusRequest.setKey(Constant.getAccountInfo("google.google_api_key"));
			}
		}).build();
		
		Plus.Activities.List listActivities = unauthenticatedPlus.activities().list(Constant.getAccountInfo("google.user_id"), "public");
		listActivities.setMaxResults(1L);
		ActivityFeed activityFeed = listActivities.execute();
		List<Activity> activities = activityFeed.getItems();
		if (activities != null && activities.size() != 0) {
			statusGoogle.readOk(activities.get(0).getUpdated().toString());
		} else {
			statusGoogle.readOk("");
		}
		
		AllStatus.google = statusGoogle;
		response.getWriter().write("ok");
	}
}
